package com.xkcoding.task.dto;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN;

@NoArgsConstructor
@Data
@Slf4j
public class AcsDoorDto {


    @JsonProperty("method")
    private String method;
    @JsonProperty("params")
    private ParamsDTO params;

    @NoArgsConstructor
    @Data
    public static class ParamsDTO {
        @JsonProperty("ability")
        private String ability;
        @JsonProperty("events")
        private List<EventsDTO> events;
        @JsonProperty("quids")
        private List<String> quids;
        @JsonProperty("sendTime")
        private String sendTime;

        @NoArgsConstructor
        @Data
        public static class EventsDTO {
            @JsonProperty("data")
            private DataDTO data;
            @JsonProperty("eventId")
            private String eventId;
            @JsonProperty("eventType")
            private Integer eventType;
            @JsonProperty("happenTime")
            private String happenTime;
            @JsonProperty("srcIndex")
            private String srcIndex;
            @JsonProperty("srcName")
            private String srcName;
            @JsonProperty("srcParentIndex")
            private String srcParentIndex;
            @JsonProperty("srcType")
            private String srcType;
            @JsonProperty("status")
            private Integer status;
            @JsonProperty("timeout")
            private Integer timeout;

            @NoArgsConstructor
            @Data
            public static class DataDTO {
                @JsonProperty("ExtAccessChannel")
                private Integer extAccessChannel;
                @JsonProperty("ExtDeviceNo")
                private Integer extDeviceNo;
                @JsonProperty("ExtEventAlarmInID")
                private Integer extEventAlarmInID;
                @JsonProperty("ExtEventAlarmOutID")
                private Integer extEventAlarmOutID;
                @JsonProperty("ExtEventCardNo")
                private String extEventCardNo;
                @JsonProperty("ExtEventCaseID")
                private Integer extEventCaseID;
                @JsonProperty("ExtEventCode")
                private Integer extEventCode;
                @JsonProperty("ExtEventCustomerNumInfo")
                private ExtEventCustomerNumInfoDTO extEventCustomerNumInfo;
                @JsonProperty("ExtEventDoorID")
                private Integer extEventDoorID;
                @JsonProperty("ExtEventID")
                private String extEventID;
                @JsonProperty("ExtEventIDCardPictureURL")
                private String extEventIDCardPictureURL;
                @JsonProperty("ExtEventIdentityCardInfo")
                private ExtEventIdentityCardInfoDTO extEventIdentityCardInfo;
                @JsonProperty("ExtEventInOut")
                private Integer extEventInOut;
                @JsonProperty("ExtEventLocalControllerID")
                private Integer extEventLocalControllerID;
                @JsonProperty("ExtEventMainDevID")
                private Integer extEventMainDevID;
                @JsonProperty("ExtEventName")
                private String extEventName;
                @JsonProperty("ExtEventPersonNo")
                private String extEventPersonNo;
                @JsonProperty("ExtEventPictureURL")
                private String extEventPictureURL;
                @JsonProperty("ExtEventReaderID")
                private Integer extEventReaderID;
                @JsonProperty("ExtEventReaderKind")
                private Integer extEventReaderKind;
                @JsonProperty("ExtEventReportChannel")
                private Integer extEventReportChannel;
                @JsonProperty("ExtEventRoleID")
                private Integer extEventRoleID;
                @JsonProperty("ExtEventSubDevID")
                private Integer extEventSubDevID;
                @JsonProperty("ExtEventSwipNum")
                private Integer extEventSwipNum;
                @JsonProperty("ExtEventType")
                private Integer extEventType;
                @JsonProperty("ExtEventVerifyID")
                private Integer extEventVerifyID;
                @JsonProperty("ExtEventWearMask")
                private Integer extEventWearMask;
                @JsonProperty("ExtEventWhiteListNo")
                private Integer extEventWhiteListNo;
                @JsonProperty("ExtReceiveTime")
                private String extReceiveTime;
                @JsonProperty("FrontSeq")
                private Integer frontSeq;
                @JsonProperty("QRCodeInfo")
                private String qRCodeInfo;
                @JsonProperty("Seq")
                private Integer seq;
                @JsonProperty("UserType")
                private Integer userType;
                @JsonProperty("helmet")
                private Integer helmet;
                @JsonProperty("meetingID")
                private String meetingID;
                @JsonProperty("svrIndexCode")
                private String svrIndexCode;

                @NoArgsConstructor
                @Data
                public static class ExtEventCustomerNumInfoDTO {
                    @JsonProperty("AccessChannel")
                    private Integer accessChannel;
                    @JsonProperty("EntryTimes")
                    private Integer entryTimes;
                    @JsonProperty("ExitTimes")
                    private Integer exitTimes;
                    @JsonProperty("TotalTimes")
                    private Integer totalTimes;
                }

                @NoArgsConstructor
                @Data
                public static class ExtEventIdentityCardInfoDTO {
                    @JsonProperty("Address")
                    private String address;
                    @JsonProperty("Birth")
                    private String birth;
                    @JsonProperty("EndDate")
                    private String endDate;
                    @JsonProperty("IdNum")
                    private String idNum;
                    @JsonProperty("IssuingAuthority")
                    private String issuingAuthority;
                    @JsonProperty("Name")
                    private String name;
                    @JsonProperty("Nation")
                    private Integer nation;
                    @JsonProperty("Sex")
                    private Integer sex;
                    @JsonProperty("StartDate")
                    private String startDate;
                    @JsonProperty("TermOfValidity")
                    private Integer termOfValidity;
                }
            }
        }
    }


    public AcsDoorUploadData buildAcsDoorUpload() {
        AcsDoorUploadData acsDoorUploadData = new AcsDoorUploadData();
        ParamsDTO.EventsDTO eventsDTO = this.getParams().getEvents().get(0);
        ParamsDTO.EventsDTO.DataDTO data = eventsDTO.getData();
        acsDoorUploadData.setVer("3.0");
        acsDoorUploadData.setTranType("10091");
        acsDoorUploadData.setTranNO(UUID.randomUUID().toString().replace("-", ""));
        acsDoorUploadData.setBackUrl("http://26.218.149.237:16000/demo/third/back");
        String format = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        acsDoorUploadData.setSendTime(format);
        acsDoorUploadData.setEquipmentId("152221010002070001");
        AcsDoorUploadData.DataDTO dataDTO = new AcsDoorUploadData.DataDTO();
        dataDTO.setGjryCyzjdm("111");
        dataDTO.setGjryZjhm(data.getExtEventIdentityCardInfo().getIdNum());
        dataDTO.setGjryXm(data.getExtEventIdentityCardInfo().getName());
        dataDTO.setGjryXb(String.valueOf(data.getExtEventIdentityCardInfo().getSex()));
        dataDTO.setGjryCsrq(data.getExtEventIdentityCardInfo().getBirth());
        dataDTO.setGjryMz(String.valueOf(data.getExtEventIdentityCardInfo().getNation()));
        dataDTO.setGjryZjkssj(data.getExtEventIdentityCardInfo().getStartDate());
        dataDTO.setGjryZjjssj(data.getExtEventIdentityCardInfo().getEndDate());
        dataDTO.setGjryHjdzQhnxxdz(data.getExtEventIdentityCardInfo().getAddress());
        try {
            String carPicUrl = "http://26.218.149.237:6040" + data.getExtEventIDCardPictureURL();
            dataDTO.setGjryZjzp(GetImageStrFromUrl(carPicUrl));
        } catch (Exception e) {
            log.error("", e);
        }
        try {
            String picUrl = "http://26.218.149.237:6040" + data.getExtEventPictureURL();
            dataDTO.setGjryCjzp(GetImageStrFromUrl(picUrl));
        } catch (Exception e) {
            log.error("", e);
        }

        dataDTO.setGjrySfrzhy(String.valueOf(1));
        dataDTO.setGjryZjxsd("90");
        String happenTime = eventsDTO.getHappenTime();
        org.joda.time.DateTime date = new org.joda.time.DateTime(happenTime);
        dataDTO.setSj(DateUtil.format(date.toDate(), NORM_DATETIME_PATTERN));
        acsDoorUploadData.setData(dataDTO);
        return acsDoorUploadData;
    }

    public String GetImageStrFromUrl(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(data.toByteArray());
        return new String(encode);
    }
}
